//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Lib.IO;
using EffiProz.Core.Errors;


namespace EffiProz.Core.RowIO
{
    /**
     * Base class for writing the data for a database row _in different formats.
     * Defines the methods that are independent of storage format and declares
     * the format-dependent methods that subclasses should define.
     *
     * @author sqlbob@users (RMP)
     * @author fredt@users
     * @version 1.7.2
     * @since 1.7.0
     */
    public abstract class RowOutputBase : ByteArrayOutputStream, RowOutputInterface
    {

        public const int CACHED_ROW_160 = 0;
        public const int CACHED_ROW_170 = 1;

        // the last column in a table is an ID that should not be written to file
        protected bool skipSystemId = false;

        /**
         *  Constructor used for persistent storage of a Table row
         *
         * @exception  IOException when an IO error is encountered
         */
        public RowOutputBase()
            : base()
        {

        }

        /**
         *  Constructor used for result sets
         *
         * @exception  IOException when an IO error is encountered
         */
        public RowOutputBase(int initialSize)
            : base(initialSize)
        {

        }

        /**
         *  Constructor used for network transmission of result sets
         *
         * @exception  IOException when an IO error is encountered
         */
        public RowOutputBase(byte[] buffer)
            : base(buffer)
        {

        }

        // fredt@users - comment - methods for writing Result column type, name and data size
        public abstract void writeEnd();

        public abstract void writeSize(int size);

        public abstract void writeType(int type);

        public abstract void writeIntData(int i, int position);

        public abstract void writeString(String s);

        // fredt@users - comment - methods used for writing each SQL type
        protected virtual void writeFieldPrefix() { }

        protected abstract void writeFieldType(SqlType type);

        protected abstract void writeNull(SqlType type);

        protected abstract void writeChar(String s, SqlType t);

        protected abstract void writeSmallint(short? o);

        protected abstract void writeInteger(int? o);

        protected abstract void writeBigint(long? o);

        protected abstract void writeReal(double? o);

        protected abstract void writeDecimal(decimal? o, SqlType type);

        protected abstract void writeBoolean(bool? o);

        protected abstract void writeDate(TimestampData o, SqlType type);

    protected abstract void writeTime(TimeData o, SqlType type);

        protected abstract void writeTimestamp(TimestampData o, SqlType type);

        protected abstract void writeYearMonthInterval(IntervalMonthData o,
                SqlType type);

        protected abstract void writeDaySecondInterval(IntervalSecondData o,
                SqlType type);

        protected abstract void writeOther(OtherData o);

        protected abstract void writeBit(BinaryData o);

        protected abstract void writeBinary(BinaryData o);

        protected abstract void writeClob(ClobData o, SqlType type);

        protected abstract void writeBlob(BlobData o, SqlType type);

        /**
         *  This method is called to write data for a table row.
         */
        public virtual void writeData(Object[] data, SqlType[] types)
        {
            writeData(types.Length, types, data, null, null);
        }

        /**
         *  This method is called directly to write data for a delete statement.
         */
        public void writeData(int l, SqlType[] types, Object[] data,
                              HashMappedList cols, int[] primaryKeys)
        {

            bool hasPK = primaryKeys != null && primaryKeys.Length != 0;
            int limit = hasPK ? primaryKeys.Length
                                  : l;

            for (int i = 0; i < limit; i++)
            {
                int j = hasPK ? primaryKeys[i]
                                 : i;
                Object o = data[j];
                SqlType t = types[j];

                if (cols != null)
                {
                    ColumnSchema col = (ColumnSchema)cols.get(j);

                    writeFieldPrefix();
                    writeString(col.getName().statementName);
                }

                if (o == null)
                {
                    writeNull(t);

                    continue;
                }

                writeFieldType(t);

                switch (t.typeCode)
                {

                    case Types.SQL_ALL_TYPES:
                        throw Error.runtimeError(ErrorCode.U_S0500,
                                                 "RowOutputBase");
                    case Types.SQL_CHAR:
                    case Types.SQL_VARCHAR:
                    case Types.VARCHAR_IGNORECASE:
                        writeChar((String)o, t);
                        break;

                    case Types.TINYINT:                     
                    case Types.SQL_SMALLINT:
                        writeSmallint(Convert.ToInt16(o));
                        break;

                    case Types.SQL_INTEGER:
                        writeInteger(Convert.ToInt32(o));
                        break;

                    case Types.SQL_BIGINT:
                        writeBigint(Convert.ToInt64(o));
                        break;

                    case Types.SQL_REAL:
                    case Types.SQL_FLOAT:
                    case Types.SQL_DOUBLE:
                        writeReal(Convert.ToDouble(o));
                        break;

                    case Types.SQL_NUMERIC:
                    case Types.SQL_DECIMAL:
                        writeDecimal(Convert.ToDecimal(o), t);
                        break;

                    case Types.SQL_BOOLEAN:
                        writeBoolean(Convert.ToBoolean(o));
                        break;

                    case Types.SQL_DATE:
                        writeDate((TimestampData)o, t);
                        break;

                    case Types.SQL_TIME:
                    case Types.SQL_TIME_WITH_TIME_ZONE:
                        writeTime((TimeData)o, t);
                        break;

                    case Types.SQL_TIMESTAMP:
                    case Types.SQL_TIMESTAMP_WITH_TIME_ZONE:
                        writeTimestamp((TimestampData)o, t);
                        break;

                    case Types.SQL_INTERVAL_YEAR:
                    case Types.SQL_INTERVAL_YEAR_TO_MONTH:
                    case Types.SQL_INTERVAL_MONTH:
                        writeYearMonthInterval((IntervalMonthData)o, t);
                        break;

                    case Types.SQL_INTERVAL_DAY:
                    case Types.SQL_INTERVAL_DAY_TO_HOUR:
                    case Types.SQL_INTERVAL_DAY_TO_MINUTE:
                    case Types.SQL_INTERVAL_DAY_TO_SECOND:
                    case Types.SQL_INTERVAL_HOUR:
                    case Types.SQL_INTERVAL_HOUR_TO_MINUTE:
                    case Types.SQL_INTERVAL_HOUR_TO_SECOND:
                    case Types.SQL_INTERVAL_MINUTE:
                    case Types.SQL_INTERVAL_MINUTE_TO_SECOND:
                    case Types.SQL_INTERVAL_SECOND:
                        writeDaySecondInterval((IntervalSecondData)o, t);
                        break;

                    case Types.OTHER:
                        writeOther((OtherData)o);
                        break;

                    case Types.SQL_BLOB:
                        writeBlob((BlobData)o, t);
                        break;

                    case Types.SQL_CLOB:
                        writeClob((ClobData)o, t);
                        break;

                    case Types.SQL_BINARY:
                    case Types.SQL_VARBINARY:
                        writeBinary((BinaryData)o);
                        break;

                    case Types.SQL_BIT:
                    case Types.SQL_BIT_VARYING:
                        writeBit((BinaryData)o);
                        break;

                    default:
                        throw Error.runtimeError(ErrorCode.U_S0500,
                                                 "RowOutputBase - "
                                                 + t.getNameString());
                }
            }
        }

        // returns the underlying HsqlByteArrayOutputStream
        public ByteArrayOutputStream getOutputStream()
        {
            return this;
        }


        // independent of the this object, calls only a static method
        public abstract int getSize(Row row);

        public abstract int getStorageSize(int size);

        public RowOutputInterface clone()
        {            
            try
            {
                return (RowOutputInterface)this; // TODOx
            }
            catch (Exception)
            {
                return null;
            }
        }


    }
}
